import 'dart:async'; // 导入 Timer 所在的库

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shop/app/modules/productContent/views/second_page_view.dart';
import 'package:shop/app/modules/productContent/views/third_page_view.dart';
import 'package:shop/tools/screenAdapter.dart';

import '../../../routes/app_pages.dart';
import '../controllers/product_content_controller.dart';
import './cart_item_num_view.dart';
import 'first_page_view.dart';

class ProductContentView extends GetView<ProductContentController> {
  const ProductContentView({super.key});

  //展示选择商品 更新流数据需要使用 GetBuilder 来渲染数据
  // 传入的index 1:代表筛选  2.代表加入购物车 3：代表立即购买
  void showBottomAttr(int action) {
    Get.bottomSheet(
      GetBuilder<ProductContentController>(
        init: controller,
        builder: (controller) {
          return Container(
            padding: EdgeInsets.all(ScreenAdapter.width(20)),
            height: ScreenAdapter.height(1200),
            width: double.infinity,
            color: Colors.white,
            child: Stack(
              children: [
                ListView(
                  children: [
                    ...controller.pcontent.value.attr!.map((value) {
                      return Wrap(
                        children: [
                          Container(
                            padding: EdgeInsets.only(
                              top: ScreenAdapter.height(20),
                              left: ScreenAdapter.width(20),
                            ),
                            width: ScreenAdapter.width(1040),
                            child: Text(
                              '${value.cate}',
                              style: const TextStyle(
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.only(
                              top: ScreenAdapter.height(20),
                              left: ScreenAdapter.width(20),
                            ),
                            width: ScreenAdapter.width(1040),
                            child: Wrap(
                              spacing: ScreenAdapter.width(20),
                              children: value.attrList!.map((e) {
                                return InkWell(
                                  onTap: () {
                                    controller.changeAttr(
                                      value.cate,
                                      e['title'],
                                    );
                                  },
                                  child: Container(
                                    child: Chip(
                                      backgroundColor: e['checked'] == true
                                          ? Colors.red
                                          : Color.fromARGB(31, 223, 213, 213),
                                      label: Text("${e["title"]}"),
                                    ),
                                  ),
                                );
                              }).toList(),
                            ),
                          ),

                          //   颜色
                        ],
                      );
                    }).toList(),
                    Padding(
                      padding: EdgeInsets.all(ScreenAdapter.height(20)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '数量',
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                          CartItemNumView(),
                        ],
                      ),
                    ),
                  ],
                ),
                Positioned(
                  top: 0,
                  right: 0,
                  child: IconButton(
                    onPressed: () {
                      Get.back();
                    },
                    icon: Icon(Icons.close),
                  ),
                ),
                Positioned(
                  bottom: 0,
                  right: 0,
                  left: 0,
                  child: action == 1
                      ? Row(
                          children: [
                            Expanded(
                              flex: 1,

                              child: Container(
                                margin: EdgeInsets.only(
                                  right: ScreenAdapter.width(20),
                                ),
                                height: ScreenAdapter.height(120),
                                child: ElevatedButton(
                                  style: ButtonStyle(
                                    backgroundColor: WidgetStatePropertyAll(
                                      Colors.orange,
                                    ),
                                    foregroundColor: WidgetStatePropertyAll(
                                      Colors.white,
                                    ),
                                    shape: WidgetStatePropertyAll(
                                      RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(10),
                                      ),
                                    ),
                                  ),
                                  onPressed: () {
                                    controller.addCart();
                                  },
                                  child: Text('加入购物车'),
                                ),
                              ),
                            ),
                            Expanded(
                              flex: 1,
                              child: Container(
                                height: ScreenAdapter.height(120),
                                margin: EdgeInsets.only(
                                  right: ScreenAdapter.width(20),
                                ),
                                child: ElevatedButton(
                                  style: ButtonStyle(
                                    backgroundColor: WidgetStatePropertyAll(
                                      Colors.red,
                                    ),
                                    foregroundColor: WidgetStatePropertyAll(
                                      Colors.white,
                                    ),
                                    shape: WidgetStatePropertyAll(
                                      RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(10),
                                      ),
                                    ),
                                  ),
                                  onPressed: () {
                                    controller.buy();
                                  },
                                  child: Text('立即购买'),
                                ),
                              ),
                            ),
                          ],
                        )
                      : Row(
                          children: [
                            Expanded(
                              flex: 1,
                              child: Container(
                                height: ScreenAdapter.height(120),
                                margin: EdgeInsets.only(
                                  right: ScreenAdapter.width(20),
                                ),
                                child: ElevatedButton(
                                  onPressed: () {
                                    if (action == 2) {
                                      controller.addCart();
                                    } else {
                                      controller.buy();
                                    }
                                  },
                                  style: ButtonStyle(
                                    backgroundColor: WidgetStatePropertyAll(
                                      Color.fromRGBO(253, 1, 0, 0.9),
                                    ),
                                    foregroundColor: WidgetStatePropertyAll(
                                      Colors.white,
                                    ),
                                    shape: WidgetStatePropertyAll(
                                      RoundedRectangleBorder(
                                        borderRadius: BorderRadius.all(
                                          Radius.circular(10),
                                        ),
                                      ),
                                    ),
                                  ),
                                  child: Text('确定'),
                                ),
                              ),
                            ),
                          ],
                        ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  // 标题
  PreferredSizeWidget _productContentAppbar(BuildContext context) {
    return AppBar(
      // 返回leading按钮
      leading: Container(
        alignment: Alignment.center,
        child: SizedBox(
          width: ScreenAdapter.width(88),
          height: ScreenAdapter.height(88),
          child: ElevatedButton(
            style: ButtonStyle(
              alignment: Alignment.center,
              padding: WidgetStateProperty.all(EdgeInsets.all(0)),
              backgroundColor: WidgetStateProperty.all(Colors.black12),
              foregroundColor: WidgetStatePropertyAll(Colors.white),
              shape: WidgetStateProperty.all(const CircleBorder()),
            ),
            onPressed: () {
              Get.back();
            },
            child: Icon(Icons.arrow_back_ios_new_outlined),
          ),
        ),
      ),
      // 中间文字
      title: _titleText(),
      centerTitle: true,
      //实现透明导航
      backgroundColor: Colors.white.withOpacity(controller.opacity.value),
      //实现透明导航
      elevation: 0,
      // 消除阴影
      actions: [
        // 左侧按钮
        appBarIcon(Icons.file_upload_outlined, context),
        SizedBox(height: 10),
        appBarIcon(Icons.more_horiz_rounded, context, right: true),
      ],
    );
  }

  // 顶部右侧icon
  Widget appBarIcon(IconData? icon, context, {right = false}) {
    return Container(
      margin: EdgeInsets.only(right: ScreenAdapter.width(20)),
      width: ScreenAdapter.width(88),
      height: ScreenAdapter.height(88),
      child: ElevatedButton(
        style: ButtonStyle(
          padding: WidgetStateProperty.all(EdgeInsets.all(0)),
          backgroundColor: WidgetStateProperty.all(Colors.black12),
          foregroundColor: WidgetStatePropertyAll(Colors.white),
          shape: WidgetStateProperty.all(const CircleBorder()),
        ),
        onPressed: () {
          if (right == true) {
            showMenu(
              color: Colors.black87.withOpacity(0.7),
              context: context,
              position: RelativeRect.fromLTRB(
                ScreenAdapter.width(800),
                ScreenAdapter.height(220),
                ScreenAdapter.width(20),
                0,
              ),
              items: [
                PopupMenuItem(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.home, color: Colors.white),
                      Text('首页', style: TextStyle(color: Colors.white)),
                    ],
                  ),
                ),
              ],
            );
          }
        },
        child: Icon(icon),
      ),
    );
  }

  // 顶部栏中间文字
  Widget _titleText() {
    return Container(
      width: ScreenAdapter.width(400),
      height: ScreenAdapter.height(96),
      child: controller.showTabs.value
          ? Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: controller.tabList.map((value) {
                return Padding(
                  padding: EdgeInsets.all(0),
                  child: InkWell(
                    onTap: () {
                      controller.changeSelectTabIndex(value['id']);
                      //   跳转到指定容器
                      if (value['id'] == 1) {
                        Scrollable.ensureVisible(
                          controller.gb1.currentContext as BuildContext,
                          duration: Duration(milliseconds: 100),
                        );
                      } else if (value['id'] == 2) {
                        Scrollable.ensureVisible(
                          controller.gb2.currentContext as BuildContext,
                          duration: Duration(milliseconds: 100),
                        );

                        //   修正
                        Timer.periodic(Duration(milliseconds: 101), (timer) {
                          controller.scrollController.jumpTo(
                            controller.scrollController.position.pixels -
                                ScreenAdapter.height(136),
                          );
                          timer.cancel();
                        });
                      } else {
                        if (controller.gb3.currentContext != null) {
                          Scrollable.ensureVisible(
                            controller.gb3.currentContext as BuildContext,
                            duration: Duration(milliseconds: 100),
                            curve: Curves.easeInOut,
                          );
                          // 先隐藏子Tab
                          controller.showSubHeaderTabs.value = false;
                          // 修正偏移量
                          // 直接滚动到推荐区域顶部
                          controller.scrollController.animateTo(
                            controller.gk3Position - ScreenAdapter.height(136),
                            duration: Duration(milliseconds: 101),
                            curve: Curves.easeInOut,
                          );
                        }
                      }
                    },
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          '${value['title']}',
                          style: TextStyle(
                            fontSize: ScreenAdapter.fontSize(36),
                          ),
                        ),
                        SizedBox(height: 6),
                        value['id'] == controller.selectIndex.value
                            ? Container(
                                margin: EdgeInsets.only(
                                  bottom: ScreenAdapter.height(10),
                                ),
                                width: ScreenAdapter.width(80),
                                height: ScreenAdapter.height(6),
                                color: Colors.red,
                              )
                            : Container(),
                      ],
                    ),
                  ),
                );
              }).toList(),
            )
          : Container(),
    );
  }

  // 内容区域
  Widget _body() {
    return SingleChildScrollView(
      controller: controller.scrollController,
      child: Column(
        children: [
          FirstPageView(showBottomAttr),
          SecondPageView(_subHeader),
          ThirdPageView(),
        ],
      ),
    );
  }

  //详情内容的tab标题
  Widget _subHeader() {
    return Container(
      color: Colors.white,
      child: Obx(
        () => Row(
          children: controller.subTabList.map((value) {
            return Expanded(
              child: InkWell(
                onTap: () {
                  controller.subSelectIndex.value = value['id'];
                  //   切换时跳转到详情顶部
                  controller.scrollController.animateTo(
                    controller.gk2Position,
                    duration: Duration(milliseconds: 500), // 动画时长（500毫秒）
                    curve: Curves.easeInOut,
                  ); // 动画曲线（缓入缓出，更自然）);
                },
                child: Container(
                  height: ScreenAdapter.height(120),
                  alignment: Alignment.center,
                  child: Text(
                    value['title'],
                    style: TextStyle(
                      color: controller.subSelectIndex == value['id']
                          ? Colors.red
                          : Colors.black38,
                    ),
                  ),
                ),
              ),
            );
          }).toList(),
        ),
      ),
    );
  }

  // 底部
  Widget _bottom() {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        height: ScreenAdapter.height(180),
        width: ScreenAdapter.width(1080),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            top: BorderSide(
              width: ScreenAdapter.width(2),
              color: Colors.black12,
            ),
          ),
        ),
        child: Row(
          children: [
            Container(
              width: ScreenAdapter.width(200),
              height: ScreenAdapter.height(160),
              child: InkWell(
                onTap: () {
                  Get.toNamed(Routes.Cart);
                },
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.shopping_cart),
                    Text(
                      '购物车',
                      style: TextStyle(fontSize: ScreenAdapter.fontSize(32)),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              flex: 1,

              child: Container(
                margin: EdgeInsets.only(right: ScreenAdapter.width(20)),
                height: ScreenAdapter.height(120),
                child: ElevatedButton(
                  style: ButtonStyle(
                    backgroundColor: WidgetStatePropertyAll(Colors.orange),
                    foregroundColor: WidgetStatePropertyAll(Colors.white),
                    shape: WidgetStatePropertyAll(
                      RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                    ),
                  ),
                  onPressed: () {
                    showBottomAttr(2);
                  },
                  child: Text('加入购物车'),
                ),
              ),
            ),
            Expanded(
              flex: 1,
              child: Container(
                height: ScreenAdapter.height(120),
                margin: EdgeInsets.only(right: ScreenAdapter.width(20)),
                child: ElevatedButton(
                  style: ButtonStyle(
                    backgroundColor: WidgetStatePropertyAll(Colors.red),
                    foregroundColor: WidgetStatePropertyAll(Colors.white),
                    shape: WidgetStatePropertyAll(
                      RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                    ),
                  ),
                  onPressed: () {
                    showBottomAttr(3);
                  },
                  child: Text('立即购买'),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 内容扩展到标题下面和实现透明导航
      extendBodyBehindAppBar: true,
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(ScreenAdapter.height(136)),
        child: Obx(() => _productContentAppbar(context)),
      ),
      // ListView 默认延迟性加载 更改成SingleChildScrollView默认加载全部组件
      body: Stack(
        children: [
          _body(),
          _bottom(),
          Obx(
            () => controller.showSubHeaderTabs.value
                ? Positioned(
                    left: 0,
                    right: 0,
                    top:
                        ScreenAdapter.getStatusBarHeight() +
                        ScreenAdapter.height(136),
                    child: _subHeader(),
                  )
                : Container(),
          ),
        ],
      ),
    );
  }
}
